import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_pad_widgets/resources/l10n/kq_pad_intl.dart';
import '../../config/kq_pad_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 选择组件
///
/// [ItemType.select]
///
/// 结合 KqPadFormEntity 使用
///
/// @author 周卓
///
class KqPadSelectItemView extends StatefulWidget {
  final KqPadFormEntity entity;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqPadFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqPadFormEntity entity)? customRightView;

  /// 选择控件箭头右侧的自定义控件
  final Widget Function(KqPadFormEntity entity)? customSelectArrowRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqPadFormEntity entity)? customBottomView;

  /// 选择控件点击回调
  final Function(KqPadFormEntity entity)? onTap;

  /// 自定义或选择控件的标题点击回调
  final Function(KqPadFormEntity entity)? onTitleTap;

  const KqPadSelectItemView(
      {Key? key,
      required this.entity,
      this.onTap,
      this.onTitleTap,
      this.customLeftView,
      this.customRightView,
      this.customSelectArrowRightView,
      this.customBottomView})
      : super(key: key);

  @override
  KqPadSelectItemViewState createState() => KqPadSelectItemViewState();
}

class KqPadSelectItemViewState extends State<KqPadSelectItemView> {
  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  @override
  void initState() {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 获取1行高度
  double measureTextHeight(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.height;
  }

  double titleWidth = 0;

  // 一行标题的高度
  double titleOneLineHeight = 0;

  calTitleWidth() {
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }

    if ((widget.entity.titleandMustOverAll != null &&
            widget.entity.titleandMustOverAll!) ||
        KqPadThemeManager.instance.getConfig().formConfig.titleandMustOverAll) {
      titleWidthString = '* $titleWidthString';
    }
    titleWidth = measureTextWidth(titleWidthString, textStyle: titleStyle);
    if (kIsWeb) {
      double fontSize = widget.entity.titleFontSize ??
          KqPadThemeManager.instance.getConfig().formConfig.titleFontSize ??
          7.dm;
      double width = (widget.entity.titleFixedWidthCharCount ?? 8) * fontSize;
      if (titleWidth < width) {
        titleWidth = width; // 最小宽度
      }
    }
    titleOneLineHeight =
        measureTextHeight(widget.entity.title, textStyle: titleStyle);
  }

  @override
  void didUpdateWidget(covariant KqPadSelectItemView oldWidget) {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor;
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);
    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }
    if ((widget.entity.titleandMustOverAll != null &&
            widget.entity.titleandMustOverAll!) ||
        KqPadThemeManager.instance.getConfig().formConfig.titleandMustOverAll) {
      titleWidthString = '* $titleWidthString';
    }
    double titleWidth =
        measureTextWidth(titleWidthString, textStyle: titleStyle);
    if (kIsWeb) {
      double fontSize = widget.entity.titleFontSize ??
          KqPadThemeManager.instance.getConfig().formConfig.titleFontSize ??
          7.dm;
      double width = (widget.entity.titleFixedWidthCharCount ?? 8) * fontSize;
      if (titleWidth < width) {
        titleWidth = width; // 最小宽度
      }
    }
    bool isHideInputBox = (widget.entity.isHideInputBox != null &&
            widget.entity.isHideInputBox!) ||
        (KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox !=
                null &&
            KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox!);

    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          KqInkWell(
            onTap: widget.entity.forceOnTap || widget.entity.isEditable()
                ? () {
                    TextFiledUtil.clearFocus(context);
                    if (widget.entity.onTap != null) {
                      widget.entity.onTap!(widget.entity);
                    }
                    if (widget.onTap != null) {
                      widget.onTap!(widget.entity);
                    }
                  }
                : null,
            enableRipple: false,
            backgroundColor: bgColor ?? Colors.transparent,
            child: Container(
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqPadThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      8.dm,
                  top: widget.entity.paddingVertical ?? 0,
                  bottom: widget.entity.paddingVertical ?? 0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  KqInkWell(
                    onTap: widget.entity.onTitleTap != null ||
                            widget.onTitleTap != null
                        ? () {
                            widget.entity.onTitleTap?.call(widget.entity);
                            widget.onTitleTap?.call(widget.entity);
                          }
                        : null,
                    child: Container(
                      padding: EdgeInsets.only(
                        right: widget.entity.titleRightMargin ?? 0,
                      ),
                      child: Row(
                        children: <Widget>[
                          /// 是否必填
                          _buildMustSign(),

                          /// 标题
                          Container(
                            width: titleWidth + (isHideInputBox ? 0 : 6.dm),
                            padding: EdgeInsets.only(
                                right: isHideInputBox ? 0 : 6.dm, top: 0.5.dm),
                            alignment: Alignment.centerRight,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                /// 左边自定义控件
                                /// 自定义布局，来自实体类
                                widget.entity.customLeftView != null
                                    ? widget
                                        .entity.customLeftView!(widget.entity)
                                    : Container(),
                                _buildOverAllTitle(titleStyle),
                                _buildTitle(titleStyle)
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  if (widget.entity.customTitleRightView != null)
                    widget.entity.customTitleRightView!(widget.entity),

                  /// 右侧文字
                  Expanded(
                    child: Container(
                      height: widget.entity.isEditable()
                          ? KqPadThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .height ??
                              20.dm
                          : null,
                      padding: widget.entity.isEditable()
                          ? EdgeInsets.only(top: 0.5.dm)
                          : EdgeInsets.symmetric(
                              vertical: widget.entity.paddingVertical ?? 7.dm),
                      margin: widget.entity.isEditable()
                          ? EdgeInsets.only(top: 2.dm, bottom: 2.dm)
                          : null,
                      decoration: widget.entity.isEditable() && !isHideInputBox
                          ? KqBoxDecoration(
                              boxShadow: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .boderColor !=
                                      null
                                  ? null
                                  : [
                                      KqBoxShadow(
                                          offset: Offset(1.dm, 1.dm),
                                          blurRadius: 0,
                                          spreadRadius: 0,
                                          color: const Color(0x80FFFFFF)),
                                      KqBoxShadow(
                                          offset: Offset(0, 1.dm),
                                          blurRadius: 3.dm,
                                          spreadRadius: 0,
                                          inset: true,
                                          color: const Color(0xFFB2B7CE)),
                                      KqBoxShadow(
                                          offset: Offset(1.dm, 1.dm),
                                          blurRadius: 1.dm,
                                          spreadRadius: 0,
                                          inset: true,
                                          color: const Color(0xFFC9CCD9)),
                                    ],
                              borderRadius: BorderRadius.circular(
                                  KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .radius ??
                                      1.dm),
                              border: Border.all(
                                  color: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .boderColor ??
                                      KqPadThemeColors.bgTransparent),
                              color: KqPadThemeColors.bgWhite,
                            )
                          : null,
                      child: Row(
                        children: [
                          /// 左边自定义控件
                          /// 自定义布局，来自实体类
                          widget.entity.customLeftView != null
                              ? widget.entity.customLeftView!(widget.entity)
                              : Container(),

                          /// 自定义布局，来自控件
                          widget.customLeftView != null
                              ? widget.customLeftView!(widget.entity)
                              : Container(),

                          // 为了和UI规范的标题和内容之间距离40
                          SizedBox(
                            width: 6.dm,
                            height: 1.dm,
                          ),

                          Expanded(
                            child: Text(
                              widget.entity.valueForShow ??
                                  (widget.entity.hint ??
                                      (widget.entity.isEditable()
                                          ? KqPadIntl
                                              .currentResource.pleaseChoose
                                          : '')),
                              textAlign: widget.entity.contentTextAlign ??
                                  (widget.entity.isEditable() && !isHideInputBox
                                      ? TextAlign.start
                                      : TextAlign.end),
                              overflow: widget.entity.overflow ??
                                  TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                color: widget.entity.valueForShow != null
                                    ? widget.entity.contentColor ??
                                        KqPadThemeColors.text59
                                    : KqPadThemeColors.textBF,
                                fontSize: widget.entity.contentFontSize ??
                                    KqPadThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .contentFontSize ??
                                    7.dm,
                              ),
                            ),
                          ),
                          Visibility(
                              visible: widget.entity.showUnit &&
                                  widget.entity.unit.isNotNullOrEmpty,
                              child: Text(
                                widget.entity.unit ?? '',
                                textAlign: TextAlign.right,
                                style: TextStyle(
                                  color: widget.entity.contentColor ??
                                      KqPadThemeColors.text59,
                                  fontSize: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .unitFontSize ??
                                      7.dm,
                                ),
                              )),

                          /// 自定义布局
                          widget.entity.customRightView != null
                              ? widget.entity.customRightView!(widget.entity)
                              : Container(),

                          /// 自定义布局
                          widget.customRightView != null
                              ? widget.customRightView!(widget.entity)
                              : Container(),

                          /// 空按钮按钮
                          if (widget.entity.enableClearButton &&
                              widget.entity.isEditable() &&
                              widget.entity.valueForShow.isNotNullOrEmpty)
                            KqInkWell(
                                onTap: () {
                                  widget.entity.onClearTap?.call(widget.entity);
                                },
                                horizontalPadding: 4.dm,
                                verticalPadding: 4.dm,
                                enableRipple: false,
                                child: Image.asset(
                                  Images.commonIcCancel16Fill,
                                  width: 7.dm,
                                  height: 7.dm,
                                  package: KqPadGlobal.packageName,
                                )),

                          /// 右侧箭头
                          Visibility(
                              visible: widget.entity.isEditable(),
                              child: Container(
                                  padding: EdgeInsets.only(left: 4.dm),
                                  margin: EdgeInsets.only(
                                      right: widget.entity
                                                      .customSelectArrowRightView !=
                                                  null ||
                                              widget.customSelectArrowRightView !=
                                                  null
                                          ? 4.r
                                          : 0),
                                  width: titleOneLineHeight,
                                  height: titleOneLineHeight,
                                  alignment: Alignment.center,
                                  child: widget.entity.selectImg ??
                                      Image.asset(
                                        // Images.commonIcJiantouRight16,
                                        Images.commonIcArrowDown,
                                        color: KqPadThemeManager.instance
                                            .getConfig()
                                            .commonConfig
                                            .rightBtnColor,
                                        height: 7.dm,
                                        fit: BoxFit.fitHeight,
                                        package: KqPadGlobal.packageName,
                                      ))),

                          if (widget.entity.isEditable())
                            SizedBox(
                              width: KqPadThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .rightMargin ??
                                  6.dm,
                            ),
                        ],
                      ),
                    ),
                  ),

                  /// 自定义布局
                  widget.entity.customSelectArrowRightView != null
                      ? widget.entity.customSelectArrowRightView!(widget.entity)
                      : Container(),

                  /// 自定义布局
                  widget.customSelectArrowRightView != null
                      ? widget.customSelectArrowRightView!(widget.entity)
                      : Container(),
                ],
              ),
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.forceHideDivider1 &&
                  !widget.entity.isEditable(),
              child: const KqPadDivider()),

          /// 分隔栏
          Visibility(
              visible: !widget.entity.hideDivider2TopMargin &&
                  widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
          Visibility(
              visible: widget.entity.showDivider2, child: const KqPadDivider()),
          Visibility(
              visible: !widget.entity.hideDivider2BottomMargin &&
                  widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
        ],
      ),
    );
  }

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }

  Widget _buildMustSign() {
    if (widget.entity.titleandMustOverAll != null) {
      if (widget.entity.titleandMustOverAll!) {
        return const SizedBox();
      }
      return _buildMustWidget();
    } else if (!KqPadThemeManager.instance
        .getConfig()
        .formConfig
        .titleandMustOverAll) {
      return _buildMustWidget();
    } else {
      return const SizedBox();
    }
  }

  Widget _buildMustWidget() {
    return Container(
      alignment: Alignment.centerRight,
      width: widget.entity.paddingHorizontal ??
          KqPadThemeManager.instance.getConfig().formConfig.paddingHorizontal ??
          8.dm,
      padding: EdgeInsets.only(right: 1.dm),
      child: Text(
        "∗",
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .mustInputFontSize ??
                7.dm,
            color: widget.entity.mustInput
                ? KqPadThemeColors.textRed
                : widget.entity.mustInputStarColor ??
                    KqPadThemeColors.bgTransparent),
      ),
    );
  }

  Widget _buildOverAllTitle(TextStyle? titleStyle) {
    if (widget.entity.titleandMustOverAll != null) {
      if (widget.entity.titleandMustOverAll! &&
          widget.entity.title.isNotEmpty) {
        return _buildOverAllTitleWiget(titleStyle);
      } else {
        return const SizedBox();
      }
    } else if ((KqPadThemeManager.instance
            .getConfig()
            .formConfig
            .titleandMustOverAll) &&
        widget.entity.title.isNotEmpty) {
      return _buildOverAllTitleWiget(titleStyle);
    } else {
      return const SizedBox();
    }
  }

  Widget _buildOverAllTitleWiget(TextStyle? titleStyle) {
    return Expanded(
      child: RichText(
          textAlign: widget.entity.titleTextAlign,
          text: TextSpan(
              text: widget.entity.mustInput ? '* ' : '',
              children: [
                TextSpan(
                    text: widget.entity.title.fixSoftWrap() ?? '',
                    style: titleStyle),
              ],
              style: TextStyle(
                fontSize: KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .mustInputFontSize ??
                    7.dm,
                color: widget.entity.mustInput
                    ? KqPadThemeColors.textRed
                    : widget.entity.mustInputStarColor ??
                        KqPadThemeColors.bgTransparent,
              ))),
    );
  }

  Widget _buildTitle(TextStyle? titleStyle) {
    if (widget.entity.titleandMustOverAll != null) {
      if (!widget.entity.titleandMustOverAll! &&
          widget.entity.title.isNotEmpty) {
        return _buildTitleWiget(titleStyle);
      } else {
        return const SizedBox();
      }
    } else if ((!KqPadThemeManager.instance
            .getConfig()
            .formConfig
            .titleandMustOverAll) &&
        widget.entity.title.isNotEmpty) {
      return _buildTitleWiget(titleStyle);
    }
    return const SizedBox();
  }

  Widget _buildTitleWiget(TextStyle? titleStyle) {
    return Expanded(
        child: Text(
      widget.entity.title.fixSoftWrap() ?? '',
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      textAlign: widget.entity.titleTextAlign,
      style: titleStyle,
    ));
  }
}
